package com.fengze.shop.common.listener;

import com.fengze.shop.common.utils.Constant;
import com.fengze.shop.model.UserInfo;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.*;

/**
 * 会话监听类
 */
@Slf4j
public class SessionListener implements HttpSessionAttributeListener, HttpSessionListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        if(httpSessionBindingEvent.equals(Constant.USER_INFO_KEY)){
            String userkey = UserOnlineState.getLoginID(((UserInfo) httpSessionBindingEvent.getValue()).getLoginType(),
                    ((UserInfo) httpSessionBindingEvent.getValue()).getLoginName());
            UserOnlineState.getState().put(userkey, 1);
        }

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        if(httpSessionBindingEvent.getName().equals(Constant.USER_INFO_KEY)){
            String userKey = UserOnlineState.getLoginID(((UserInfo) httpSessionBindingEvent.getValue()).getLoginType(),
                    ((UserInfo) httpSessionBindingEvent.getValue()).getLoginName());

            UserOnlineState.getState().remove(userKey);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    /**
     * 创建session会话执行，为了统计在线用户人数
     * @param httpSessionEvent
     */
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        Constant.USER_ONLINE_NUM++;// 获得当前在线人数，并将其加一
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        try {
            //销毁会话的时候，需要将在线人数减一
            HttpSession session = httpSessionEvent.getSession();
            if(Constant.USER_ONLINE_NUM > 0){
                Constant.USER_ONLINE_NUM--;//在线人数减一
            }

            session.invalidate();
        } catch (Exception e) {
            log.error("sessionDestroyed == 在线用户统计失败, {}",e);
        }
    }
}
